<template>
  <div class="expert-evaluate-page">
    <!-- 倒计时提示（任务终止后5分钟内） -->
    <div v-if="taskStatus === 'countdown'" class="countdown-wrapper">
      <div class="status-icon">
        <i class="iconfont icon-time"></i>
      </div>
      <div class="status-content">
        <div class="status-title">任务已终止</div>
        <div class="countdown-content">
          <span class="countdown-label">剩余打分时间</span>
          <div class="count-down">
            {{ formatCountdown(remainingTime) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 打分结束提示页面 -->
    <div v-if="taskStatus === 'ended'" class="end-task-page">
      <div class="end-content">
        <div class="end-title">评估时间已结束</div>
        <div class="end-subtitle">感谢您的参与，本次评估任务已经完成</div>
        <div class="end-info">
          <p>• 任务已于 {{ formatEndTime }} 终止</p>
          <p>
            •
            {{ systemConfig?.finalScoreCountdown }}分钟补充打分时间已结束
          </p>
          <p>• 您可以关闭此页面</p>
        </div>
        <div class="end-actions">
          <button class="end-btn" @click="handleReturnHome">关闭页面</button>
        </div>
      </div>
    </div>
    <!-- 评估内容区域（任务进行中或倒计时阶段） -->
    <div v-if="taskStatus === 'active' || taskStatus === 'countdown'">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-title">专家评估</div>
      </div>

      <!-- 评估信息 -->
      <div class="section-wrapper evaluate-person-wrapper">
        <div class="section-title">评估专家</div>
        <div class="section-content" style="display: flex; align-items: center">
          <span style="padding-right: 5px; color: red">*</span>
          <el-input
            v-model="evaluatePerson"
            placeholder="请输入您的姓名"
            require
          />
        </div>
      </div>

      <!-- 评估信息 -->
      <div v-if="false" class="section-wrapper">
        <div class="section-title">评估信息</div>
        <div class="section-content">
          本次评估任务对广播电视传播清晰度进行主观质量评价，专家需根据考察要求对不同时间点评估结果进行打分，确保打分观点准确。
        </div>
      </div>

      <!-- 评估要求 -->
      <div class="section-wrapper">
        <div class="section-title">评估要求</div>
        <div class="section-content" style="padding-left: 5px">
          <div>
            请您在视频播放期间开展评估工作，还请于<span class="strong-text"
              >{{
                taskData?.planDuration ? taskData.planDuration / 60 : "--"
              }}分钟</span
            >内完成各指标的分组打分，总共
            <span class="strong-text">{{ timeSegments.length || "--" }} 组</span
            >。
          </div>
          <div>
            各评估标段满分
            <span class="strong-text">10分</span
            >，评分可参考指定时间点对应的指标成绩；
          </div>
          <div>建议您结合视频播放进程同步进行评估工作。</div>
        </div>
      </div>

      <!-- 专家评估表 -->
      <div class="evaluation-table-wrapper">
        <div class="section-title">评估表</div>
        <div class="base-info">
          <div class="base-info-item" style="width: 50%">
            <div class="base-info-item-label">任务名称:</div>
            <div class="base-info-item-value">
              {{ taskData?.name }}
            </div>
          </div>
          <div class="base-info-item" style="width: 50%">
            <div class="base-info-item-label">任务说明:</div>
            <div class="base-info-item-value">
              {{ taskData?.desc }}
            </div>
          </div>
        </div>
        <div class="table-container">
          <el-table
            :data="quotaList"
            stripe
            fit
            class="self-stripe-table"
            height="100%"
          >
            <el-table-column label="一级指标" width="200">
              <template #default="scope">
                <div class="quota-cell">{{ scope.row.name }}</div>
              </template>
            </el-table-column>
            <el-table-column label="二级指标" min-width="150">
              <template #default="scope">
                <div class="quota-cell">
                  {{ scope.row.evaluationCriteria }}
                </div>
                <div class="quota-cell">
                  {{ scope.row.evaluationLevel }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="false"
              :label="`等级说明 (${10}分)`"
              width="200"
            >
              <template #default="scope">
                <div class="range-cell">
                  <div class="score-range good">
                    优：{{
                      scope.row.evaluationScore
                        ? (scope.row.evaluationScore * 0.8).toFixed(0)
                        : 8
                    }}-{{ scope.row.evaluationScore || 10 }}分
                  </div>
                  <div class="score-range fair">
                    良：{{
                      scope.row.evaluationScore
                        ? (scope.row.evaluationScore * 0.5).toFixed(0)
                        : 5
                    }}-{{
                      scope.row.evaluationScore
                        ? (scope.row.evaluationScore * 0.7).toFixed(0)
                        : 7
                    }}分
                  </div>
                  <div class="score-range poor">
                    差：{{
                      scope.row.evaluationScore
                        ? (scope.row.evaluationScore * 0.0).toFixed(0)
                        : 0
                    }}-{{
                      scope.row.evaluationScore
                        ? (scope.row.evaluationScore * 0.4).toFixed(0)
                        : 4
                    }}分
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(segment, index) in timeSegments"
              :key="segment.label"
              :label="segment.label"
              align="center"
              width="150"
            >
              <template #default="scope">
                <div class="score-cell">
                  <el-input-number
                    v-if="scoreData[scope.row.id]"
                    v-model="scoreData[scope.row.id][index]"
                    :min="0"
                    :max="scope.row.evaluationScore || 10"
                    :precision="0"
                    controls-position="right"
                    class="score-input"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 备注说明 -->
      <div class="section-wrapper">
        <div class="section-title">备注说明：</div>
        <div class="textarea-wrapper">
          <textarea
            v-model="remarkContent"
            placeholder="输入您对本次评估的备注说明..."
            class="remark-textarea"
          ></textarea>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="bottom-actions">
        <button class="action-btn cancel-btn" @click="handleCancel">
          取消
        </button>
        <button class="action-btn save-btn" @click="handleSave">保存</button>
        <button class="action-btn confirm-btn" @click="handleConfirm">
          确认
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getQuotaListAPI, QuotaType } from "@/api/service/quota";
import {
  addOrUpdateEvaluateTaskResultAPI,
  getEvaluateTaskResultAPI,
  EvaluateTaskResultType,
} from "@/api/service/evaluateTaskResult";
import {
  getevaluateTaskListAPI,
  EvaluateTaskType,
} from "@/api/service/evaluateTask";
import {
  getSystemConfigAPI,
  GetSystemConfigResponseType,
} from "@/api/service/sysConfig";

const route = useRoute();

// 路由参数
const taskId = ref<string>("");
const templateId = ref<string>("");
const expertId = ref<string>("");

const evaluatePerson = ref<string>("");

// 页面数据
const quotaList = ref<QuotaType[]>([]);
const remarkContent = ref<string>("");
const timeSegments = ref<Array<{ label: string; duration: number }>>([]);
const scoreData = ref<Record<string, Record<string, number>>>({});
const taskData = ref<EvaluateTaskType | null>(null);

// 任务状态管理
const taskEndTime = ref<string>("");
const currentTime = ref<number>(Date.now());
const countdownTimerInterval = ref<number | null>(null);
const statusCheckInterval = ref<number | null>(null);
const lastTaskStatus = ref<string>("");

// 系统配置
const systemConfig = ref<GetSystemConfigResponseType | null>(null);
// 获取系统配置
const getSystemConfig = async () => {
  getSystemConfigAPI().then((_data: any) => {
    const data = _data as GetSystemConfigResponseType;
    systemConfig.value = {
      finalScoreCountdown: data.finalScoreCountdown - 1,
    };
    COUNTDOWN_DURATION = (data.finalScoreCountdown - 1) * 60 * 1000;
  });
};
getSystemConfig();

// 5分钟倒计时时长（毫秒）
let COUNTDOWN_DURATION = 5 * 60 * 1000;
// 状态检查间隔（毫秒）- 每3秒检查一次
const STATUS_CHECK_INTERVAL = 3 * 1000;

// 计算属性：剩余时间
const remainingTime = computed(() => {
  if (!taskEndTime.value) return 0;
  const endTime = new Date(taskEndTime.value).getTime();
  const remaining = endTime + COUNTDOWN_DURATION - currentTime.value;
  return Math.max(0, remaining);
});

// 计算属性：任务状态
const taskStatus = computed(() => {
  if (!taskData.value) return "loading";

  if (taskData.value.execStatus < 3) {
    return "active"; // 任务进行中
  } else if (taskData.value.execStatus === 3) {
    if (remainingTime.value > 0) {
      return "countdown"; // 5分钟倒计时中
    } else {
      return "ended"; // 已结束
    }
  }
  return "loading";
});

// 计算属性：格式化结束时间
const formatEndTime = computed(() => {
  if (!taskEndTime.value) return "";
  const date = new Date(taskEndTime.value);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
});

// 格式化倒计时显示
const formatCountdown = (duration: number): string => {
  if (duration <= 0) {
    return "00:00";
  }

  const totalSeconds = Math.floor(duration / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
};

// 启动倒计时定时器
const startCountdownTimer = () => {
  if (countdownTimerInterval.value) return; // 防止重复启动

  countdownTimerInterval.value = window.setInterval(() => {
    currentTime.value = Date.now();
  }, 1000);
};

// 停止倒计时定时器
const stopCountdownTimer = () => {
  if (countdownTimerInterval.value) {
    clearInterval(countdownTimerInterval.value);
    countdownTimerInterval.value = null;
  }
};

// 启动状态检查定时器
const startStatusCheckTimer = () => {
  if (statusCheckInterval.value) return; // 防止重复启动

  statusCheckInterval.value = window.setInterval(async () => {
    await checkTaskStatusChange();
  }, STATUS_CHECK_INTERVAL);
};

// 停止状态检查定时器
const stopStatusCheckTimer = () => {
  if (statusCheckInterval.value) {
    clearInterval(statusCheckInterval.value);
    statusCheckInterval.value = null;
  }
};

// 停止所有定时器
const stopAllTimers = () => {
  stopCountdownTimer();
  stopStatusCheckTimer();
};

// 检查任务状态变化
const checkTaskStatusChange = async () => {
  try {
    const oldStatus = lastTaskStatus.value;

    // 重新获取任务数据
    await loadTaskData();

    const newStatus = taskStatus.value;

    // 如果状态发生变化，处理相应逻辑
    if (oldStatus && oldStatus !== newStatus) {
      await handleStatusChange(oldStatus, newStatus);
    }

    // 更新记录的状态
    lastTaskStatus.value = newStatus;
  } catch (error) {
    console.error("检查任务状态失败:", error);
  }
};

// 处理状态变化
const handleStatusChange = async (oldStatus: string, newStatus: string) => {
  console.log(`任务状态变化: ${oldStatus} -> ${newStatus}`);

  // 状态变化处理逻辑
  if (oldStatus === "active" && newStatus === "countdown") {
    // 从进行中变为倒计时：启动倒计时定时器
    startCountdownTimer();
    ElMessage.info(
      `任务已终止，开始${systemConfig.value?.finalScoreCountdown}分钟补充打分时间`
    );

    // 确保评估数据已加载（通常已经加载了，但为了保险）
    if (quotaList.value.length === 0) {
      await loadTemplateQuotas();
      await loadExistingResults();
    }
  } else if (oldStatus === "countdown" && newStatus === "ended") {
    // 从倒计时变为结束：停止倒计时定时器
    stopCountdownTimer();
    ElMessage.info("评估时间已结束");
  } else if (oldStatus === "active" && newStatus === "ended") {
    // 从进行中直接变为结束：确保没有倒计时定时器
    stopCountdownTimer();
    ElMessage.info("评估时间已结束");
  } else if (newStatus === "countdown" && !countdownTimerInterval.value) {
    // 确保倒计时状态下有倒计时定时器
    startCountdownTimer();

    // 确保评估数据已加载
    if (quotaList.value.length === 0) {
      await loadTemplateQuotas();
      await loadExistingResults();
    }
  } else if (newStatus !== "countdown" && countdownTimerInterval.value) {
    // 非倒计时状态下停止倒计时定时器
    stopCountdownTimer();
  }

  // 如果变为ended状态，停止状态检查定时器
  if (newStatus === "ended") {
    // 延迟停止状态检查，给用户一些时间看到最终状态
    setTimeout(() => {
      stopAllTimers();
    }, 5000);
  }
};

// 关闭页面
const handleReturnHome = () => {
  window.close();
};

// 初始化数据
onMounted(async () => {
  // 获取路由参数
  taskId.value = (route.query.taskId as string) || "";
  templateId.value = (route.query.templateId as string) || "";
  expertId.value = (route.query.expertId as string) || "";

  if (taskId.value && templateId.value) {
    // 首先加载任务数据
    await loadTaskData();

    // 根据任务状态决定是否需要启动定时器和加载评估数据
    if (taskData.value) {
      const currentStatus = taskStatus.value;
      lastTaskStatus.value = currentStatus; // 记录初始状态

      if (currentStatus === "countdown") {
        // 倒计时状态：启动倒计时定时器 + 加载评估数据
        startCountdownTimer();
        await loadTemplateQuotas();
        await loadExistingResults();
      } else if (currentStatus === "active") {
        // 进行中状态：仅加载评估数据，无需倒计时定时器
        await loadTemplateQuotas();
        await loadExistingResults();
      }
      // ended 状态：什么都不需要加载

      // 启动状态检查定时器（除非已经是ended状态）
      if (currentStatus !== "ended") {
        startStatusCheckTimer();
      }
    }
  } else {
    ElMessage.warning("缺少必要的参数：taskId 或 templateId");
  }
});

// 组件卸载时清理所有定时器
onUnmounted(() => {
  stopAllTimers();
});

// 获取模板指标列表
const loadTemplateQuotas = async () => {
  try {
    const response = await getQuotaListAPI({
      templateId: templateId.value,
    });

    quotaList.value =
      (response as any).data || (response as unknown as QuotaType[]);
    quotaList.value.forEach((quota) => {
      if (quota.evaluationCriteria) {
        quota.evaluationCriteria = formatEvaluationCriteria(
          quota.evaluationCriteria
        );
      }
      if (quota.evaluationLevel) {
        quota.evaluationLevel = formatEvaluationCriteria(quota.evaluationLevel);
      }
    });
  } catch (error) {
    ElMessage.error("获取评估指标失败");
  }
};

// 初始化评分数据结构
const initializeScoreData = () => {
  quotaList.value.forEach((quota) => {
    if (quota.id) {
      const quotaId = quota.id;
      // 如果该指标还没有数据，则初始化
      if (!scoreData.value[quotaId]) {
        scoreData.value[quotaId] = {};
      }

      // 为每个时间段初始化分数（如果还没有分数的话）
      timeSegments.value.forEach((segment, index) => {
        if (scoreData.value[quotaId][index] === undefined) {
          scoreData.value[quotaId][index] = 5;
        }
      });
    }
  });
};

// 加载任务数据
const loadTaskData = async () => {
  try {
    const response = await getevaluateTaskListAPI({
      currentPage: 1,
      numPerPage: 1000,
    });

    const taskList =
      (response as any).data?.list || (response as any).list || [];
    const currentTask = taskList.find(
      (task: EvaluateTaskType) => task.id === taskId.value
    );

    if (currentTask) {
      taskData.value = currentTask;

      // 计算时间分段（所有状态都需要）
      calculateTimeSegments(currentTask.planDuration, currentTask.segmentTime);

      // 处理任务状态
      if (currentTask.execStatus === 3) {
        taskEndTime.value = currentTask.endTime || "";
        currentTime.value = Date.now();
      } else if (currentTask.execStatus < 3) {
        taskEndTime.value = "";
      }
    } else {
      ElMessage.warning("未找到对应的评估任务");
    }
  } catch (error) {
    ElMessage.error("获取任务数据失败");
  }
};

// 计算时间分段
const calculateTimeSegments = (planDuration: number, segmentTime: number) => {
  const segments: Array<{ label: string; duration: number }> = [];
  let currentTime = 0;

  while (currentTime < planDuration) {
    const remainingTime = planDuration - currentTime;

    // 如果剩余时间不足一个完整分段，且已经有分段存在，则合并到最后一个分段
    if (remainingTime < segmentTime && segments.length > 0) {
      // 将剩余时间合并到最后一个分段，累计时间为总时长
      segments[segments.length - 1].duration = planDuration;
      segments[segments.length - 1].label = `${(planDuration / 60).toFixed(
        0
      )}分钟打分`;
      break;
    }

    const nextTime = currentTime + segmentTime;
    segments.push({
      label: `${(nextTime / 60).toFixed(0)}分钟打分`,
      duration: nextTime,
    });

    currentTime = nextTime;
  }

  timeSegments.value = segments;
};

// 获取已有的评价结果
const loadExistingResults = async () => {
  try {
    if (!expertId.value) {
      return; // 如果没有专家ID，不需要获取已有结果
    }

    const response = await getEvaluateTaskResultAPI({
      evaluateTaskId: taskId.value,
      expertId: expertId.value,
    });

    const existingResults =
      (response as any).data ||
      (response as unknown as EvaluateTaskResultType[]);

    if (
      existingResults &&
      Array.isArray(existingResults) &&
      existingResults.length > 0
    ) {
      // 解析已有的评价结果并回显到界面
      parseAndFillExistingResults(existingResults);
    }

    existingResults.forEach((result: EvaluateTaskResultType) => {
      if (result.isTotalScore) {
        remarkContent.value = result.note;
        evaluatePerson.value = result.evaluatePerson;
      }
    });
  } catch (error) {
    // 没有已有结果或获取失败，不影响正常使用
    console.log("获取已有评价结果失败或无数据：", error);
  } finally {
    // 无论是否有已有结果，都要确保评分数据结构完整
    initializeScoreData();
  }
};

// 解析并填充已有的评价结果
const parseAndFillExistingResults = (results: EvaluateTaskResultType[]) => {
  results.forEach((result) => {
    if (result.quotaId && result.segmentScore) {
      try {
        // 解析 segmentScore 格式 "{1:7,2:8}"
        const segmentScores = JSON.parse(
          result.segmentScore.replace(/(\w+):/g, '"$1":')
        );

        // 将分数填入 scoreData
        if (!scoreData.value[result.quotaId]) {
          scoreData.value[result.quotaId] = {};
        }

        Object.keys(segmentScores).forEach((segmentIndex) => {
          const index = parseInt(segmentIndex) - 1; // 转换为从0开始的索引
          if (index >= 0 && index < timeSegments.value.length) {
            scoreData.value[result.quotaId][index] =
              segmentScores[segmentIndex];
          }
        });
      } catch (error) {
        console.error("解析分段分数失败：", error);
      }
    }
  });
};

// 处理取消
const handleCancel = () => {
  window.close();
};

// 处理保存
const handleSave = () => {
  handleConfirm();
};

// 处理确认提交
const confirmLoading = ref(false);
const handleConfirm = async () => {
  try {
    if (!evaluatePerson.value) {
      ElMessage.warning("请输入您的姓名");
      return;
    }
    if (confirmLoading.value) {
      return;
    }
    confirmLoading.value = true;
    // 构建提交数据
    const evaluateResultList: EvaluateTaskResultType[] = [];

    quotaList.value.forEach((quota) => {
      if (quota.id) {
        const quotaIdStr = quota.id || "";

        // 收集当前指标的所有分段分值
        const segmentScores: Record<string, number> = {};
        let totalScore = 0;
        let segmentCount = 0;

        timeSegments.value.forEach((segment, index) => {
          const score = scoreData.value[quotaIdStr]?.[index] || 0;
          segmentScores[`${index + 1}`] = score; // 下标从1开始
          totalScore += score;
          segmentCount++;
        });

        // 计算平均分
        const averageScore = segmentCount > 0 ? totalScore / segmentCount : 0;

        // 将分段分值组合成"{1:7,2:8}"格式
        const segmentScoreStr = JSON.stringify(segmentScores).replace(/"/g, "");

        if (quotaIdStr) {
          evaluateResultList.push({
            id: "",
            taskId: taskId.value,
            templateId: templateId.value,
            quotaId: quotaIdStr,
            quotaName: quota.name || "",
            averageScore: Math.round(averageScore * 100) / 100, // 保留2位小数
            absoluteScore: 0,
            medianScore: 0,
            standardDeviationScore: 0,
            segmentScore: segmentScoreStr,
            isTotalScore: false,
            expertId: expertId.value,
            note: "",
            evaluatePerson: "",
            createTime: "",
            updateTime: "",
          });
        }
      }
    });

    // 提交数据
    await addOrUpdateEvaluateTaskResultAPI({
      evaluateTaskId: taskId.value,
      templateId: templateId.value,
      expertId: expertId.value,
      note: remarkContent.value,
      evaluatePerson: evaluatePerson.value,
      evaluateResultList: evaluateResultList,
    });

    ElMessage.success("提交成功");
  } catch (error) {
    ElMessage.error("提交失败");
  } finally {
    confirmLoading.value = false;
  }
};

// 处理二级指标输入 - 自动添加实心圆点
function formatEvaluationCriteria(text: string): string {
  if (!text || !text.trim()) return text;

  const lines = text
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line.length > 0)
    .map((line) => {
      // 如果行已经有实心圆点，就不重复添加
      if (line.startsWith("● ")) {
        return line;
      }
      // 移除可能存在的其他项目符号（如"1、"、"•"、"-"等）
      const cleanLine = line.replace(/^[1-9]+[、.)]\s*|^[•\-*]\s*|^●\s*/, "");
      return cleanLine ? `● ${cleanLine}` : "";
    })
    .filter((line) => line.length > 0);

  return lines.join("\n");
}
</script>

<style scoped lang="scss">
.expert-evaluate-page {
  position: relative;
  min-height: 100vh;
  background: url("~@/assets/images/bg.png") no-repeat center top;
  background-size: 100% 100%;
  padding: 0;
}

.page-header {
  text-align: center;
  padding: 1.5rem 0;

  .header-title {
    font-family: "douyinbold";
    font-size: $font-size-system-Logo;
    color: $text-color-brand;
  }
}
.evaluate-person-wrapper {
  .el-input {
    height: 5rem;
  }
}

.section-wrapper {
  background-color: #fff;
  margin: 0 1rem 1rem 1rem;
  padding: 1.5rem;
  border-radius: 0.8rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .section-title {
    font-size: $font-size-page-menu;
    color: $color-brand;
    margin-bottom: 1rem;
  }

  .section-content {
    font-size: $font-size-block-title;
    color: $text-color-regular;
  }
  .strong-text {
    padding: 0 0.5rem;
    color: $color-brand;
    font-weight: bold;
  }
}

.evaluation-table-wrapper {
  background-color: #fff;
  margin: 2rem 1rem;
  padding: 1.5rem;
  border-radius: 0.8rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 50vh;

  .section-title {
    font-size: $font-size-page-menu;
    color: $color-brand;
    font-weight: 500;
    margin-bottom: 1rem;
    flex-shrink: 0;
  }
  .base-info {
    display: flex;
    flex-wrap: wrap;
    border: 1px solid $border-color-primary;
    border-radius: 0.8rem;
    padding: 1rem 0 0 0;
    margin-bottom: 1rem;
    width: 100%;
    .base-info-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      margin-bottom: 1rem;
      color: $text-color-regular;
      .base-info-item-label {
        width: 10rem;
        padding-right: 1rem;
        text-align: right;
        font-size: $font-size-block-title;
      }
      .base-info-item-value {
        font-size: $font-size-block-title;
      }
      .el-input {
        width: calc(100% - 15rem);
      }
    }
  }

  .quota-cell {
    color: $text-color-regular;
    text-align: left;
    white-space: pre-wrap;
    line-height: 1.8;
  }

  .range-cell {
    text-align: left;

    .score-range {
      margin: 0.3rem 0;
      font-size: $font-size-block-title;
      line-height: 1.4;

      &.good {
        color: $color-success;
      }

      &.fair {
        color: $color-warning;
      }

      &.poor {
        color: $color-danger;
      }
    }
  }

  .score-cell {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;

    .score-input {
      width: 100px;
    }
  }
}

.textarea-wrapper {
  .remark-textarea {
    width: 100%;
    min-height: 8rem;
    padding: 1rem;
    border: 1px solid $border-color-primary;
    border-radius: 0.8rem;
    font-size: $font-size-block-title;
    font-family: inherit;
    resize: vertical;
    color: $text-color-regular;

    &:focus {
      outline: none;
      border-color: $color-brand;
      box-shadow: 0 0 0 2px rgba($color-brand, 0.2);
    }

    &::placeholder {
      color: $text-color-placeholder;
      opacity: 0.7;
    }
  }
}

.bottom-actions {
  position: relative;
  z-index: 10;
  display: flex;
  justify-content: space-around;
  padding: 2rem 1rem;
  background-color: white;
  position: sticky;
  bottom: 0;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);

  .action-btn {
    flex: 1;
    margin: 0 0.5rem;
    padding: 1.2rem 0;
    border: none;
    border-radius: 0.8rem;
    font-size: $font-size-block-title;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &.cancel-btn {
      background-color: $text-color-placeholder;
      color: $text-color-regular;

      &:hover {
        background-color: darken($text-color-placeholder, 5%);
      }
    }

    &.save-btn {
      background-color: $color-warning;
      color: white;

      &:hover {
        background-color: darken($color-warning, 8%);
      }
    }

    &.confirm-btn {
      background-color: $color-brand;
      color: white;

      &:hover {
        background-color: darken($color-brand, 8%);
      }
    }

    &:active {
      transform: translateY(1px);
    }
  }
}

:deep(.el-table) {
  .el-table__header {
    .el-table__cell {
      font-size: $font-size-block-title;
      color: $text-color-primary !important;
    }
  }
  .el-table__cell {
    padding: 1rem 0.8rem;
    font-size: $font-size-base;
    color: $text-color-regular !important;
  }
}

// 倒计时
.countdown-wrapper {
  position: fixed;
  top: 1.5rem;
  right: 1.5rem;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 1.6rem;
  padding: 2rem 3rem;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.95) 0%,
    rgba(248, 250, 252, 0.95) 100%
  );
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  min-width: 32rem;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15), 0 4px 12px rgba(0, 0, 0, 0.12);
  }

  .status-icon {
    flex-shrink: 0;
    width: 5rem;
    height: 5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(
      135deg,
      $color-brand 0%,
      lighten($color-brand, 10%) 100%
    );
    border-radius: 50%;
    color: white;
    font-size: 2.4rem;
    box-shadow: 0 4px 12px rgba($color-brand, 0.3);
    animation: pulse 2s ease-in-out infinite;
  }

  .status-content {
    flex: 1;
    text-align: left;

    .status-title {
      font-size: 1.8rem;
      font-weight: 600;
      color: #475569;
      margin-bottom: 0.6rem;
      letter-spacing: 0.3px;
    }

    .countdown-content {
      .countdown-label {
        font-size: 1.5rem;
        color: #64748b;
        display: block;
        margin-bottom: 0.4rem;
      }

      .count-down {
        font-family: "Consolas", "Monaco", "Lucida Console", monospace;
        font-size: 2.8rem;
        font-weight: 700;
        color: $color-brand;
        text-shadow: 0 1px 2px rgba($color-brand, 0.3);
        letter-spacing: 2px;
      }
    }
  }
}

// 打分结束页面样式
.end-task-page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: url("~@/assets/images/bg.png") no-repeat center top;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .end-content {
    background: white;
    border-radius: 2rem;
    padding: 4rem;
    text-align: center;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
    max-width: 40rem;
    width: 90%;
    animation: slideUp 0.6s ease-out;

    .end-title {
      font-size: $font-size-system-Logo;
      font-weight: 700;
      color: #2d3748;
      margin-bottom: 1rem;
      animation: fadeInUp 0.6s ease-out 0.4s both;
    }

    .end-subtitle {
      font-size: $font-size-base;
      color: #718096;
      margin-bottom: 3rem;
      line-height: 1.6;
      animation: fadeInUp 0.6s ease-out 0.6s both;
    }

    .end-info {
      text-align: left;
      background: #f8fafc;
      padding: 2rem;
      border-radius: 1rem;
      margin-bottom: 3rem;
      animation: fadeInUp 0.6s ease-out 0.8s both;

      p {
        margin: 0.8rem 0;
        color: #4a5568;
        font-size: $font-size-base;
        line-height: 1.6;

        &:first-child {
          margin-top: 0;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .end-actions {
      animation: fadeInUp 0.6s ease-out 1s both;
    }

    .end-btn {
      background: linear-gradient(
        135deg,
        $color-brand 0%,
        lighten($color-brand, 10%) 100%
      );
      color: white;
      border: none;
      padding: 1rem 3rem;
      border-radius: 2rem;
      font-size: $font-size-base;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 4px 15px rgba($color-brand, 0.3);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba($color-brand, 0.4);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 呼吸动画效果
@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

// 动画定义
@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
